package com.renu.jdependencyanalyser.utils;

import com.renu.jdependencyanalyser.cons.ProjectCons;

import javax.swing.*;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class MyFileUtil {
    // 读取文件并转换为字节数组的方法
    public static byte[] readFileToBytes(String filePath) {
        File file = new File(filePath);
        FileInputStream fis = null;
        byte[] bytesArray = null;

        try {
            // 创建 FileInputStream 对象
            fis = new FileInputStream(file);
            bytesArray = new byte[(int) file.length()];

            // 读取文件内容到字节数组
            fis.read(bytesArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭 FileInputStream
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytesArray;
    }

    public static  Set<String> findxxPath(File file,String suffix){
        Set<String> result = new HashSet<String>();
        File[] children = file.listFiles();
        for (File child : children) {
            String path = child.getAbsolutePath();
            if (path.endsWith(suffix)) {
                result.add(path);
            }

        }
        for (File child : children) {
            if (child.isDirectory()) {
                result.addAll(findxxPath(child,suffix));
            }
        }
        return result;
    }
    public static Set<String> findJarPath(File file) {
        Set<String> result = new HashSet<String>();
        File[] children = file.listFiles();
        for (File child : children) {
            String jarPath = child.getAbsolutePath();
            if (jarPath.endsWith(".jar")) {
                result.add(jarPath);
            }
        }
        for (File child : children) {
            if (child.isDirectory()) {
                result.addAll(findJarPath(child));
            }
        }
        return result;
    }



    public static String extractClassSigFromJavaPath(String javaPath) {
        String classSig = javaPath.replace(".java", "");
        int index = -1;
      if (classSig.contains(File.separator +"main" + File.separator +"java")){
           index =classSig.indexOf(File.separator +"main" + File.separator +"java")+10;
      }else if (classSig.contains(File.separator +"test" + File.separator +"java")){
          index = classSig.indexOf(File.separator +"test" + File.separator +"java")+10;
        }else if (classSig.contains(File.separator +"src")){
          index = classSig.indexOf(File.separator +"src")+4;
      }
      classSig = classSig.substring(index+1).replace(File.separator ,".");
      return classSig;
    }

    public static String classSig2PckName(String classSig) {
        int index = classSig.lastIndexOf(".");
        if (index != -1)
            return classSig.substring(0,index);
        return  classSig;
    }

    public static Set<String> findClassePathsFromJar(String jarPath) {
        HashSet<String> classSet = new HashSet<>();
        try(JarFile jarfile = new JarFile(jarPath)) {
            Enumeration<JarEntry> entries = jarfile.entries();
            Iterator<JarEntry> jarEntryIterator = entries.asIterator();
            while(jarEntryIterator.hasNext()){
                JarEntry jarEntry = jarEntryIterator.next();
                if (jarEntry.getName().endsWith(".class")) {
                    classSet.add(jarEntry.getName());
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return classSet;

    }

    /**
     *
     * @param classPath : org/xmlpull/v1/XmlPullParser.class
     * @return
     */
    public static String classPath2ClassSig(String classPath) {
        return classPath.replace(".class","").replace(File.separator,".");
    }

    public static byte[] convertFileToByteArray(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try{
            byte[] buffer = new byte[1024];
            int bytesRead;

            // 从文件输入流读取数据到字节数组输出流
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }



        }finally {
            fileInputStream.close();
            byteArrayOutputStream.close();
        }

        // 获取字节数组
        return byteArrayOutputStream.toByteArray();
    }

    public static String extractClassSigFromClassPath(String classPath) {
        String basePath = MyProjectUtil.projectBasePath + ProjectCons.SCR_INPUT_PATH;
        return classPath.substring(basePath.length()+1).replace(".class","").replace(File.separator,".");
    }

    public static String convertStringSymbol(String str, String from, String to) {
        return str.replace(from,to);
    }


    public static String convertPathToDot(String str) {
        return  convertStringSymbol(str,File.separator,".");
    }

    public static String JavaPath2ClassSig(String path) {
        int index = path.indexOf(MyProjectUtil.projectBasePath) + MyProjectUtil.projectBasePath.length();
        return path.substring(index).replace(".java","").replace(File.separator,".");
    }

    public static String convert2MthdSig(String classSig, String returnType, String methodName, String parameters) {
        StringBuilder sb = new StringBuilder(classSig);
        sb.append("::\n").append(returnType).append(" ").append(methodName).append(parameters);
        return sb.toString();
    }


 public  static   void createOutDir(String dir ) {
        // 指定目录路径


        // 将路径字符串转为 Path 对象
        Path path = Paths.get(dir);

        // 检查目录是否存在
        if (!Files.exists(path)) {
            try {
                // 创建目录
                Files.createDirectories(path);
                System.out.println("Directory created successfully.");
            } catch (Exception e) {
                System.err.println("Failed to create directory: " + e.getMessage());
            }
        } else {
            System.out.println("Directory already exists.");
        }
    }


    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        boolean delete = file.delete();
        if (delete){
            System.out.println("文件删除成功");
        }else{
            System.out.println("文件删除失败");
        }


    }
}
